﻿<template>
  <div class="return-order-management">
    <div class="page-header">
      <h2>采购退货管理</h2>
      <button @click="openAdd" class="btn-primary">新增退货单</button>
    </div>

    <div class="search-panel">
      <div class="search-form">
        <div class="form-group">
          <label>退货单号</label>
          <input v-model="query.returnNo" @keyup.enter="search" placeholder="请输入退货单号" class="form-input" />
        </div>
        <div class="form-group">
          <label>原采购单号</label>
          <input v-model="query.orderNo" @keyup.enter="search" placeholder="请输入原采购单号" class="form-input" />
        </div>
        <div class="form-group">
          <label>状态</label>
          <select v-model="query.status" class="form-select">
            <option value="">全部</option>
            <option value="0">草稿</option>
            <option value="1">待审核</option>
            <option value="2">已通过</option>
            <option value="3">已拒绝</option>
          </select>
        </div>
        <button @click="search" class="btn-primary">搜索</button>
        <button @click="reset" class="btn-secondary">重置</button>
      </div>
    </div>

    <div class="data-panel">
      <div class="panel-header">
        <h3>退货单列表</h3>
        <p>管理所有采购退货单信息</p>
      </div>
      
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="list.length === 0" class="empty">暂无数据</div>
      <div v-else class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>退货单号</th>
              <th>原采购单号</th>
              <th>退货金额</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id">
              <td>{{ item.returnNo || "-" }}</td>
              <td>{{ item.orderNo || "-" }}</td>
              <td>{{ item.totalReturnAmount || "0.00" }}</td>
              <td>
                <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
              </td>
              <td>{{ formatDate(item.createTime) }}</td>
              <td class="action-cell">
                <button @click="viewDetail(item)" class="btn-view">查看</button>
                <button @click="editItem(item)" :disabled="item.status !== 0" class="btn-edit">编辑</button>
                <button @click="submitForAudit(item)" :disabled="item.status !== 0" class="btn-submit">提交审核</button>
                <button @click="deleteItem(item)" :disabled="item.status !== 0" class="btn-delete">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="pagination">
      <button @click="prevPage" :disabled="pageNum === 1" class="btn-page">上一页</button>
      <span class="page-info">第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，总计 {{ total }} 条</span>
      <button @click="nextPage" :disabled="pageNum * pageSize >= total" class="btn-page">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { apiGet, apiPost, apiDelete } from '../../utils/api.js'

// 响应式数据
const loading = ref(false)
const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 对话框状态
const showDialog = ref(false)
const showDetail = ref(false)
const isEdit = ref(false)
const detail = ref(null)

// 搜索条件
const query = reactive({
  returnNo: '',
  orderNo: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: null,
  orderId: '',
  returnNo: '',
  returnReason: '',
  remark: '',
  items: []
})

// 采购订单列表
const purchaseOrders = ref([])

// 计算属性
const totalAmount = computed(() => {
  return form.items.reduce((sum, item) => sum + (item.returnAmount || 0), 0)
})

const canSubmit = computed(() => {
  return form.orderId && form.returnNo && form.items.length > 0
})

// 生命周期
onMounted(() => {
  load()
  loadPurchaseOrders()
})

// 方法
async function load() {
  loading.value = true
  try {
    const params = {
      current: pageNum.value,
      size: pageSize.value,
      ...query
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/purchase-return-order/page${qs ? `?${qs}` : ''}`)
    
    console.log('采购退货单API响应数据:', response)
    
    // 处理不同的响应结构
    let records = []
    let totalCount = 0

    if (response.data) {
      // 如果响应有data字段
      records = response.data.records || response.data.list || []
      totalCount = response.data.total || 0
    } else if (response.records) {
      // 如果响应直接有records字段
      records = response.records || []
      totalCount = response.total || 0
    } else if (Array.isArray(response)) {
      // 如果响应直接是数组
      records = response
      totalCount = response.length
    }

    console.log('解析后的records:', records)
    console.log('解析后的total:', totalCount)

    list.value = records.map(r => ({ ...r, id: r.id != null ? String(r.id) : r.id }))
    total.value = totalCount

    console.log('处理后的数据:', list.value)
  } catch (error) {
    console.error('加载失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

async function loadPurchaseOrders() {
  try {
    const response = await apiGet('/procure-service/purchase-order/page?current=1&size=1000')
    if (response.data && response.data.records) {
      purchaseOrders.value = response.data.records
    } else if (response.records) {
      purchaseOrders.value = response.records
    }
  } catch (error) {
    console.error('加载采购订单失败:', error)
    purchaseOrders.value = []
  }
}

function search() {
  pageNum.value = 1
  load()
}

function reset() {
  query.returnNo = ''
  query.orderNo = ''
  query.status = ''
  pageNum.value = 1
  load()
}

function prevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    load()
  }
}

function nextPage() {
  if (pageNum.value * pageSize.value < total.value) {
    pageNum.value++
    load()
  }
}

function openAdd() {
  isEdit.value = false
  resetForm()
  showDialog.value = true
}

function editItem(item) {
  if (item.status !== 0) {
    alert('只有草稿状态的退货单可以编辑')
    return
  }
  
  isEdit.value = true
  form.id = item.id
  form.orderId = item.orderId
  form.returnNo = item.returnNo
  form.returnReason = item.returnReason
  form.remark = item.remark
  form.items = item.items || []
  showDialog.value = true
}

function viewDetail(item) {
  detail.value = item
  showDetail.value = true
}

function closeDialog() {
  showDialog.value = false
  resetForm()
}

function closeDetail() {
  showDetail.value = false
  detail.value = null
}

function resetForm() {
  form.id = null
  form.orderId = ''
  form.returnNo = ''
  form.returnReason = ''
  form.remark = ''
  form.items = []
}

function onOrderChange() {
  if (form.orderId) {
    const order = purchaseOrders.value.find(o => o.id == form.orderId)
    if (order) {
      form.items = (order.items || []).map(item => ({
        ...item,
        returnQuantity: 0,
        returnUnitPrice: item.unitPrice || 0,
        returnAmount: 0
      }))
    }
  } else {
    form.items = []
  }
}

function addItem() {
  if (!form.orderId) {
    alert('请先选择采购订单')
    return
  }
  
  const order = purchaseOrders.value.find(o => o.id == form.orderId)
  if (order && order.items) {
    order.items.forEach(item => {
      if (!form.items.find(i => i.productId === item.productId)) {
        form.items.push({
          ...item,
          returnQuantity: 0,
          returnUnitPrice: item.unitPrice || 0,
          returnAmount: 0
        })
      }
    })
  }
}

function removeItem(index) {
  form.items.splice(index, 1)
}

function calculateItemAmount(item, index) {
  item.returnAmount = (item.returnQuantity || 0) * (item.returnUnitPrice || 0)
}

async function submitForm() {
  if (!canSubmit.value) {
    alert('请填写完整信息')
    return
  }
  
  try {
    const data = {
      ...form,
      totalReturnAmount: totalAmount.value
    }
    
    if (isEdit.value) {
      await apiPost(`/procure-service/purchase-return-order/update`, data)
    } else {
      await apiPost('/procure-service/purchase-return-order/create', data)
    }
    
    alert(isEdit.value ? '更新成功' : '创建成功')
    closeDialog()
    load()
  } catch (error) {
    console.error('提交失败:', error)
    alert('操作失败')
  }
}

async function submitForAudit(item) {
  if (item.status !== 0) {
    alert('只有草稿状态的退货单可以提交审核')
    return
  }
  
  if (!confirm('确定要提交审核吗？')) {
    return
  }
  
  try {
    await apiPost(`/procure-service/purchase-return-order/submit/${item.id}`)
    alert('提交审核成功')
    load()
  } catch (error) {
    console.error('提交审核失败:', error)
    alert('提交审核失败')
  }
}

async function deleteItem(item) {
  if (item.status !== 0) {
    alert('只有草稿状态的退货单可以删除')
    return
  }
  
  if (!confirm('确定要删除这个退货单吗？')) {
    return
  }
  
  try {
    await apiDelete(`/procure-service/purchase-return-order/${item.id}`)
    alert('删除成功')
    load()
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败')
  }
}

function getStatusText(status) {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已通过',
    3: '已拒绝'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    0: 'status-draft',
    1: 'status-pending',
    2: 'status-approved',
    3: 'status-rejected'
  }
  return classMap[status] || ''
}

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.return-order-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.btn-primary {
  padding: 10px 20px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: #3b82f6;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-primary:disabled {
  background: #9ca3af;
  border-color: #9ca3af;
  cursor: not-allowed;
}

.btn-secondary {
  padding: 10px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.search-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  width: 200px;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.data-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.panel-header p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.loading, .empty {
  padding: 40px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  color: #666;
  background: #f8f9fa;
  font-weight: 600;
  white-space: nowrap;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.action-cell {
  white-space: nowrap;
}

.btn-view, .btn-edit, .btn-submit, .btn-delete {
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-view {
  color: #909399;
  border-color: #909399;
}

.btn-view:hover {
  background: #909399;
  color: #fff;
}

.btn-edit {
  color: #e6a23c;
  border-color: #e6a23c;
}

.btn-edit:hover {
  background: #e6a23c;
  color: #fff;
}

.btn-submit {
  color: #67c23a;
  border-color: #67c23a;
}

.btn-submit:hover {
  background: #67c23a;
  color: #fff;
}

.btn-delete {
  color: #f56c6c;
  border-color: #f56c6c;
}

.btn-delete:hover {
  background: #f56c6c;
  color: #fff;
}

.btn-view:disabled, .btn-edit:disabled, .btn-submit:disabled, .btn-delete:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.status-draft {
  color: #909399;
  background: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-pending {
  color: #e6a23c;
  background: #fdf6ec;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-approved {
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-rejected {
  color: #f56c6c;
  background: #fef0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.btn-page {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-page:hover:not(:disabled) {
  background: #f8f9fa;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 1000px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-close:hover {
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-textarea {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  width: 100%;
  min-height: 80px;
  resize: vertical;
}

.items-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.btn-add-item {
  padding: 6px 12px;
  border: 1px solid #3b82f6;
  border-radius: 4px;
  background: #3b82f6;
  color: #fff;
  cursor: pointer;
  font-size: 12px;
}

.btn-add-item:hover {
  background: #2563eb;
}

.empty-items {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.items-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.items-table th,
.items-table td {
  padding: 8px;
  border: 1px solid #ebeef5;
  text-align: left;
}

.items-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #666;
}

.form-input-small {
  padding: 4px 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  width: 80px;
}

.btn-remove {
  padding: 2px 6px;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  background: #fff;
  color: #f56c6c;
  cursor: pointer;
  font-size: 12px;
}

.btn-remove:hover {
  background: #f56c6c;
  color: #fff;
}

.total-section {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.total-row {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
}

.total-amount {
  color: #3b82f6;
  font-size: 18px;
}

.dialog-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #3b82f6;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 100px;
}

.detail-item span {
  color: #333;
}
</style>
